package com.minidao.framework.rowMapper;

import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.Map;

import org.apache.commons.collections.map.LinkedMap;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.support.JdbcUtils;

public class MapRowMapper implements RowMapper<Map<String, Object>> {

	@Override
	public Map<String, Object> mapRow(ResultSet resultSet, int rowNum) throws SQLException {
		ResultSetMetaData rsmd = resultSet.getMetaData();
		int columnCount = rsmd.getColumnCount();
		Map<String, Object> mapOfColValues = createColumnMap(columnCount);
		for (int i = 1; i <= columnCount; i++) {
			String key = getColumnKey(rsmd, i);
			Object obj = getColumnValue(resultSet, i);
			mapOfColValues.put(key, obj);
		}
		return mapOfColValues;
	}

	protected Map<String, Object> createColumnMap(int columnCount) {
		return new LinkedMap(columnCount);
	}

	protected String getColumnKey(ResultSetMetaData rsmd, int index) throws SQLException {
		return JdbcUtils.lookupColumnName(rsmd, index);
	}

	protected Object getColumnValue(ResultSet rs, int index) throws SQLException {
		return JdbcUtils.getResultSetValue(rs, index);
	}

}
